package com.szcinda.call.service;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.szcinda.call.Result;
import com.szcinda.call.SnowFlakeFactory2;
import com.szcinda.call.repository.UserAccount;
import com.szcinda.call.repository.UserAccountRepository;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Transactional
public class UserAccountServiceImpl implements UserAccountService {


    private final UserAccountRepository userAccountRepository;
    private final SnowFlakeFactory2 snowFlakeFactory2;

    private static final ObjectMapper objectMapper = new ObjectMapper();

    public UserAccountServiceImpl(UserAccountRepository userAccountRepository) {
        this.userAccountRepository = userAccountRepository;
        this.snowFlakeFactory2 = SnowFlakeFactory2.getInstance();
    }

    @Override
    public Result<String> update(UserAccountDto accountDto) {
        UserAccount userAccount = userAccountRepository.findByUserName(accountDto.getUserName());
        if (userAccount == null) {
            userAccount = new UserAccount();
            BeanUtils.copyProperties(accountDto, userAccount);
        }
        List<SiteDto> siteDtos = null;
        try {
            siteDtos = objectMapper.readValue(userAccount.getJson(), new TypeReference<List<SiteDto>>() {
            });
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            return Result.fail("转换JSON出错");
        }
        Assert.isTrue(siteDtos != null && siteDtos.size() <= 4, "同一个登录账号添加站点不允许超过4个");
        userAccount.setId(snowFlakeFactory2.nextId("SA"));
        userAccountRepository.save(userAccount);
        return Result.success();
    }

    @Override
    public Result<String> check(String userName, SiteDto siteDto) {
        UserAccount userAccount = userAccountRepository.findByUserName(userName);
        if (userAccount == null) {
            // 新建
            userAccount = new UserAccount();
            userAccount.setUserName(userName);
            List<SiteDto> siteDtos = new ArrayList<>();
            siteDtos.add(siteDto);
            try {
                String value = objectMapper.writeValueAsString(siteDtos);
                userAccount.setJson(value);
                userAccount.setId(snowFlakeFactory2.nextId("UA"));
                userAccountRepository.save(userAccount);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
                return Result.fail("参数siteDto结构错误");
            }
            return Result.success();
        }
        if (StringUtils.isEmpty(userAccount.getJson())) {
            // 修改
            List<SiteDto> siteDtos = new ArrayList<>();
            siteDtos.add(siteDto);
            try {
                String value = objectMapper.writeValueAsString(siteDtos);
                userAccount.setJson(value);
                userAccountRepository.save(userAccount);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
                return Result.fail("参数siteDto结构错误");
            }
            return Result.success();
        }
        List<SiteDto> siteDtos = null;
        try {
            siteDtos = objectMapper.readValue(userAccount.getJson(), new TypeReference<List<SiteDto>>() {
            });
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            return Result.fail("转换JSON出错");
        }
        Assert.isTrue(siteDto != null, "参数SiteDto不能为空");
        if (siteDto.getSites() == null || siteDto.getSites().size() == 0) {
            List<SiteDto> newDtos = siteDtos.parallelStream().filter(dto -> !dto.getUserName().equals(siteDto.getUserName())).collect(Collectors.toList());
            try {
                String value = objectMapper.writeValueAsString(newDtos);
                userAccount.setJson(value);
                userAccountRepository.save(userAccount);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
                return Result.fail("参数siteDto结构错误");
            }
            return Result.success();
        }
        if (siteDtos != null && siteDtos.size() <= 4) {
            List<SiteDto> newDtos = siteDtos.parallelStream().filter(dto -> !dto.getUserName().equals(siteDto.getUserName())).collect(Collectors.toList());
            if (newDtos.size() < 4) {
                newDtos.add(siteDto);
                try {
                    String value = objectMapper.writeValueAsString(newDtos);
                    userAccount.setJson(value);
                    userAccountRepository.save(userAccount);
                } catch (JsonProcessingException e) {
                    e.printStackTrace();
                    return Result.fail("参数siteDto结构错误");
                }
                return Result.success();
            }
        }
        return Result.fail("同一个登录账号添加站点不允许超过4个");
    }

    @Override
    public List<SiteDto> getSite(String userName) {
        UserAccount userAccount = userAccountRepository.findByUserName(userName);
        if (userAccount == null) {
            return new ArrayList<>();
        }
        List<SiteDto> siteDtos = null;
        try {
            siteDtos = objectMapper.readValue(userAccount.getJson(), new TypeReference<List<SiteDto>>() {
            });
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return siteDtos;
    }
}
